package com.sikaryofficial.backend.aspect;

import com.sikaryofficial.backend.annotation.TenantFilter;
import com.sikaryofficial.backend.constant.TenantConstant;
import com.sikaryofficial.backend.holder.TenantFilterContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author 33
 * 功能：多租户过滤拦截切面
 * 时间：2023/11/30 19:15
 */
@Aspect
@Component
@Slf4j
public class TenantFilterAspect {

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.sikaryofficial.backend.annotation.TenantFilter)")
    public void tenantValidateMethod() {
    }

    /**
     * 环绕方法
     *
     * @param joinPoint 切点
     * @return 切点
     */
    @Around(value = "tenantValidateMethod()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取方法
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        TenantFilter tenantFilter = method.getAnnotation(TenantFilter.class);
        boolean value = tenantFilter.value();
        //将当前注解的值设置到ThreadLocal中，提供给当前线程在执行该方法时进行租户过滤判断
        TenantFilterContextHolder.set(TenantConstant.TENANT_OPEN_SWITCH, value);
        return joinPoint.proceed(joinPoint.getArgs());
    }

    @After(value = "tenantValidateMethod()")
    public void after() {
        TenantFilterContextHolder.remove();
    }
}
